<template>
  <div>
    <!-- 搜索栏 -->
    <a-card style="margin-bottom: 16px;">
      <a-form layout="inline">
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="车牌号/品牌/车型/客户"
            style="width: 200px;"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <SearchOutlined />
              查询
            </a-button>
            <a-button @click="handleReset">
              <RedoOutlined />
              重置
            </a-button>
            <a-button type="primary" @click="handleAdd">
              <PlusOutlined />
              新增
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 表格 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'plateNumber'">
            <a-tag color="blue">{{ record.plateNumber }}</a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定删除该车辆吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" danger size="small">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      width="700px"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="客户" required>
          <a-select
            v-model:value="formData.customerId"
            placeholder="请选择客户"
            show-search
            :filter-option="filterOption"
          >
            <a-select-option v-for="customer in customerList" :key="customer.id" :value="customer.id">
              {{ customer.name }} - {{ customer.phone }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="车牌号" required>
          <a-input v-model:value="formData.plateNumber" placeholder="请输入车牌号" />
        </a-form-item>
        <a-form-item label="品牌" required>
          <a-input v-model:value="formData.brand" placeholder="如：宝马" />
        </a-form-item>
        <a-form-item label="车型" required>
          <a-input v-model:value="formData.model" placeholder="如：BMW 320Li" />
        </a-form-item>
        <a-form-item label="颜色">
          <a-input v-model:value="formData.color" placeholder="请输入颜色" />
        </a-form-item>
        <a-form-item label="车架号">
          <a-input v-model:value="formData.vin" placeholder="请输入车架号" />
        </a-form-item>
        <a-form-item label="发动机号">
          <a-input v-model:value="formData.engineNumber" placeholder="请输入发动机号" />
        </a-form-item>
        <a-form-item label="购买日期">
          <a-date-picker
            v-model:value="formData.purchaseDate"
            style="width: 100%;"
            placeholder="请选择购买日期"
          />
        </a-form-item>
        <a-form-item label="当前里程">
          <a-input-number
            v-model:value="formData.mileage"
            :min="0"
            placeholder="请输入当前里程（公里）"
            style="width: 100%;"
          />
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  getVehiclePage,
  addVehicle,
  updateVehicle,
  deleteVehicle
} from '@/api/vehicle'
import { getCustomerList } from '@/api/customer'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'

const loading = ref(false)
const tableData = ref([])
const customerList = ref([])
const searchForm = reactive({
  keyword: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `共 ${total} 条`
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '车牌号', dataIndex: 'plateNumber', key: 'plateNumber', width: 120 },
  { title: '品牌', dataIndex: 'brand', key: 'brand' },
  { title: '车型', dataIndex: 'model', key: 'model' },
  { title: '颜色', dataIndex: 'color', key: 'color', width: 80 },
  { title: '车主', dataIndex: 'customerName', key: 'customerName' },
  { title: '联系电话', dataIndex: 'customerPhone', key: 'customerPhone', width: 120 },
  { title: '里程(km)', dataIndex: 'mileage', key: 'mileage', width: 100 },
  { title: '操作', key: 'action', width: 150, fixed: 'right' }
]

const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('新增车辆')
const isEdit = ref(false)
const formData = reactive({
  id: null,
  customerId: null,
  plateNumber: '',
  brand: '',
  model: '',
  color: '',
  vin: '',
  engineNumber: '',
  purchaseDate: null,
  mileage: 0,
  remark: ''
})

// 加载客户列表
const loadCustomerList = async () => {
  try {
    const res = await getCustomerList()
    customerList.value = res.data
  } catch (error) {
    console.error('加载客户列表失败：', error)
  }
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const res = await getVehiclePage({
      current: pagination.current,
      size: pagination.pageSize,
      keyword: searchForm.keyword
    })
    tableData.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  loadTableData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  pagination.current = 1
  loadTableData()
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadTableData()
}

// 新增
const handleAdd = () => {
  modalTitle.value = '新增车辆'
  isEdit.value = false
  Object.assign(formData, {
    id: null,
    customerId: null,
    plateNumber: '',
    brand: '',
    model: '',
    color: '',
    vin: '',
    engineNumber: '',
    purchaseDate: null,
    mileage: 0,
    remark: ''
  })
  modalVisible.value = true
}

// 编辑
const handleEdit = (record) => {
  modalTitle.value = '编辑车辆'
  isEdit.value = true
  Object.assign(formData, {
    ...record,
    purchaseDate: record.purchaseDate ? dayjs(record.purchaseDate) : null
  })
  modalVisible.value = true
}

// 删除
const handleDelete = async (id) => {
  try {
    await deleteVehicle(id)
    message.success('删除成功')
    loadTableData()
  } catch (error) {
    console.error('删除失败：', error)
  }
}

// 弹窗确认
const handleModalOk = async () => {
  if (!formData.customerId || !formData.plateNumber || !formData.brand || !formData.model) {
    message.warning('请填写必填项')
    return
  }
  
  modalLoading.value = true
  try {
    const data = {
      ...formData,
      purchaseDate: formData.purchaseDate ? dayjs(formData.purchaseDate).format('YYYY-MM-DD') : null
    }
    
    if (isEdit.value) {
      await updateVehicle(data)
      message.success('更新成功')
    } else {
      await addVehicle(data)
      message.success('新增成功')
    }
    modalVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('操作失败：', error)
  } finally {
    modalLoading.value = false
  }
}

// 选择器筛选
const filterOption = (input, option) => {
  return option.children[0].children.toLowerCase().includes(input.toLowerCase())
}

onMounted(() => {
  loadCustomerList()
  loadTableData()
})
</script>

<style scoped>
</style>

